// 学生答题模块
const db = wx.cloud.database();
const paperCollection = db.collection('papers');
const recordCollection = db.collection('records');
const _ = db.command;

/**
 * 通过考试码获取试卷
 * @param {String} examCode 考试码
 * @returns {Promise} 试卷信息
 */
async function getPaperByExamCode(examCode) {
  try {
    // 查询考试码
    const codeRes = await db.collection('exam_codes').where({
      code: examCode,
      status: 'active',
      expireTime: _.gt(db.serverDate())
    }).get();
    
    if (codeRes.data.length === 0) {
      return {
        success: false,
        message: '考试码无效或已过期'
      };
    }
    
    const codeInfo = codeRes.data[0];
    
    // 获取试卷信息
    const paperId = codeInfo.paperId;
    const paperRes = await paperCollection.doc(paperId).get();
    
    if (!paperRes.data) {
      return {
        success: false,
        message: '试卷不存在'
      };
    }
    
    // 检查试卷状态
    if (paperRes.data.status !== 'published') {
      return {
        success: false,
        message: '该试卷未发布'
      };
    }
    
    // 检查用户是否已答过此试卷
    const userInfo = await wx.cloud.callFunction({
      name: 'getUser',
      data: {}
    });
    
    const recordRes = await recordCollection.where({
      userId: userInfo.result.openid,
      paperId: paperId,
      status: 'completed'
    }).count();
    
    const hasCompleted = recordRes.total > 0;
    
    return {
      success: true,
      paper: paperRes.data,
      hasCompleted
    };
  } catch (error) {
    console.error('获取试卷失败', error);
    return {
      success: false,
      message: '获取试卷失败: ' + error.message
    };
  }
}

/**
 * 开始答题
 * @param {String} paperId 试卷ID
 * @returns {Promise} 开始结果
 */
async function startExam(paperId) {
  try {
    // 获取用户信息
    const userInfo = await wx.cloud.callFunction({
      name: 'getUser',
      data: {}
    });
    
    const userId = userInfo.result.openid;
    
    // 获取试卷信息
    const paperRes = await paperCollection.doc(paperId).get();
    
    if (!paperRes.data) {
      return {
        success: false,
        message: '试卷不存在'
      };
    }
    
    // 创建答题记录
    const record = {
      userId,
      paperId,
      paperTitle: paperRes.data.title,
      subject: paperRes.data.subject,
      answers: [],
      startTime: db.serverDate(),
      status: 'in_progress',
      duration: 0
    };
    
    const recordRes = await recordCollection.add({
      data: record
    });
    
    return {
      success: true,
      recordId: recordRes._id,
      message: '开始答题成功'
    };
  } catch (error) {
    console.error('开始答题失败', error);
    return {
      success: false,
      message: '开始答题失败: ' + error.message
    };
  }
}

/**
 * 保存答题内容
 * @param {String} recordId 记录ID
 * @param {Object} answerData 答案数据
 * @returns {Promise} 保存结果
 */
async function saveAnswer(recordId, answerData) {
  try {
    const { questionId, userAnswer } = answerData;
    
    // 获取记录信息
    const recordRes = await recordCollection.doc(recordId).get();
    
    if (!recordRes.data) {
      return {
        success: false,
        message: '答题记录不存在'
      };
    }
    
    // 检查记录状态
    if (recordRes.data.status !== 'in_progress') {
      return {
        success: false,
        message: '该答题已结束，无法继续作答'
      };
    }
    
    // 获取试卷和题目信息
    const paperRes = await paperCollection.doc(recordRes.data.paperId).get();
    const paper = paperRes.data;
    
    // 查找题目信息
    const questionInfo = paper.questions.find(q => q.questionId === questionId);
    
    if (!questionInfo) {
      return {
        success: false,
        message: '题目不存在'
      };
    }
    
    // 获取题目详情以检查答案
    const questionRes = await db.collection('questions').doc(questionId).get();
    const question = questionRes.data;
    
    // 检查是否为客观题
    const isObjective = ['single_choice', 'multiple_choice', 'true_false'].includes(question.type);
    
    // 对客观题进行自动判分
    let isCorrect = false;
    if (isObjective) {
      if (question.type === 'multiple_choice') {
        // 多选题判断
        const correctAnswer = question.content.answer.split(',').sort().join(',');
        const userAnswerSorted = userAnswer.split(',').sort().join(',');
        isCorrect = correctAnswer === userAnswerSorted;
      } else {
        // 单选题和判断题判断
        isCorrect = question.content.answer === userAnswer;
      }
    }
    
    // 计算得分
    const score = isObjective && isCorrect ? questionInfo.score : 0;
    
    // 更新记录中的答案
    const answers = recordRes.data.answers || [];
    const existingAnswerIndex = answers.findIndex(a => a.questionId === questionId);
    
    if (existingAnswerIndex >= 0) {
      // 更新已有答案
      answers[existingAnswerIndex] = {
        questionId,
        userAnswer,
        isCorrect,
        score: isObjective ? score : null, // 主观题先设为null，待教师批改
        updateTime: db.serverDate()
      };
    } else {
      // 添加新答案
      answers.push({
        questionId,
        userAnswer,
        isCorrect,
        score: isObjective ? score : null,
        createTime: db.serverDate()
      });
    }
    
    // 更新记录
    await recordCollection.doc(recordId).update({
      data: {
        answers,
        updateTime: db.serverDate()
      }
    });
    
    return {
      success: true,
      isCorrect,
      score: isObjective ? score : null,
      message: '保存答案成功'
    };
  } catch (error) {
    console.error('保存答案失败', error);
    return {
      success: false,
      message: '保存答案失败: ' + error.message
    };
  }
}

/**
 * 提交试卷
 * @param {String} recordId 记录ID
 * @returns {Promise} 提交结果
 */
async function submitExam(recordId) {
  try {
    // 获取记录信息
    const recordRes = await recordCollection.doc(recordId).get();
    
    if (!recordRes.data) {
      return {
        success: false,
        message: '答题记录不存在'
      };
    }
    
    // 检查记录状态
    if (recordRes.data.status !== 'in_progress') {
      return {
        success: false,
        message: '该答题已结束，无法重复提交'
      };
    }
    
    // 计算答题时间（分钟）
    const startTime = new Date(recordRes.data.startTime);
    const endTime = new Date();
    const duration = Math.round((endTime - startTime) / 60000);
    
    // 计算总分
    const answers = recordRes.data.answers || [];
    let totalScore = 0;
    
    answers.forEach(answer => {
      if (answer.score !== null && answer.score !== undefined) {
        totalScore += answer.score;
      }
    });
    
    // 更新记录
    await recordCollection.doc(recordId).update({
      data: {
        status: 'completed',
        endTime: db.serverDate(),
        duration,
        totalScore,
        updateTime: db.serverDate()
      }
    });
    
    return {
      success: true,
      duration,
      totalScore,
      message: '提交试卷成功'
    };
  } catch (error) {
    console.error('提交试卷失败', error);
    return {
      success: false,
      message: '提交试卷失败: ' + error.message
    };
  }
}

/**
 * 获取错题集
 * @param {Object} params 查询参数
 * @returns {Promise} 错题集
 */
async function getWrongQuestions(params = {}) {
  try {
    const { subject, page = 1, size = 20 } = params;
    
    // 获取用户信息
    const userInfo = await wx.cloud.callFunction({
      name: 'getUser',
      data: {}
    });
    
    const userId = userInfo.result.openid;
    
    // 调用云函数获取错题集
    const result = await wx.cloud.callFunction({
      name: 'getWrongQuestions',
      data: {
        userId,
        subject,
        page,
        size
      }
    });
    
    return {
      success: true,
      ...result.result
    };
  } catch (error) {
    console.error('获取错题集失败', error);
    return {
      success: false,
      message: '获取错题集失败: ' + error.message
    };
  }
}

/**
 * 获取答题记录列表
 * @param {Object} params 查询参数
 * @returns {Promise} 答题记录
 */
async function getExamRecords(params = {}) {
  try {
    const { subject, page = 1, size = 20 } = params;
    
    // 获取用户信息
    const userInfo = await wx.cloud.callFunction({
      name: 'getUser',
      data: {}
    });
    
    const userId = userInfo.result.openid;
    
    let query = recordCollection.where({
      userId,
      status: 'completed'
    });
    
    if (subject) {
      query = query.where({
        subject
      });
    }
    
    // 获取总数
    const countResult = await query.count();
    const total = countResult.total;
    
    // 分页查询
    const result = await query
      .orderBy('endTime', 'desc')
      .skip((page - 1) * size)
      .limit(size)
      .get();
    
    return {
      success: true,
      records: result.data,
      total,
      page,
      size
    };
  } catch (error) {
    console.error('获取答题记录失败', error);
    return {
      success: false,
      message: '获取答题记录失败: ' + error.message
    };
  }
}

module.exports = {
  getPaperByExamCode,
  startExam,
  saveAnswer,
  submitExam,
  getWrongQuestions,
  getExamRecords
}; 